// 键生成工具

export interface KeyOptions {
  prefix?: string;
  separator?: string;
  suffix?: string;
  namespace?: string;
  version?: string;
}

export class KeyGenerator {
  private options: Required<KeyOptions>;

  constructor(options: KeyOptions = {}) {
    this.options = {
      prefix: '',
      separator: ':',
      suffix: '',
      namespace: '',
      version: '',
      ...options,
    };
  }

  /**
   * 生成基础键
   */
  generate(...parts: (string | number)[]): string {
    const keyParts: string[] = [];

    // 添加命名空间
    if (this.options.namespace) {
      keyParts.push(this.options.namespace);
    }

    // 添加前缀
    if (this.options.prefix) {
      keyParts.push(this.options.prefix);
    }

    // 添加版本
    if (this.options.version) {
      keyParts.push(`v${this.options.version}`);
    }

    // 添加主要部分
    keyParts.push(...parts.map(part => String(part)));

    // 添加后缀
    if (this.options.suffix) {
      keyParts.push(this.options.suffix);
    }

    return keyParts.join(this.options.separator);
  }

  /**
   * 生成缓存键
   */
  cache(key: string, ...tags: string[]): string {
    const parts = ['cache', key];
    if (tags.length > 0) {
      parts.push('tags', tags.join(','));
    }
    return this.generate(...parts);
  }

  /**
   * 生成会话键
   */
  session(sessionId: string): string {
    return this.generate('session', sessionId);
  }

  /**
   * 生成用户会话键
   */
  userSessions(userId: string): string {
    return this.generate('user', userId, 'sessions');
  }

  /**
   * 生成队列键
   */
  queue(
    queueName: string,
    type: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'priority' = 'waiting'
  ): string {
    return this.generate('queue', queueName, type);
  }

  /**
   * 生成作业键
   */
  job(jobId: string): string {
    return this.generate('job', jobId);
  }

  /**
   * 生成计数器键
   */
  counter(name: string, window?: string): string {
    const parts = ['counter', name];
    if (window) {
      parts.push(window);
    }
    return this.generate(...parts);
  }

  /**
   * 生成集合键
   */
  set(name: string, type: 'set' | 'zset' = 'set'): string {
    return this.generate(type, name);
  }

  /**
   * 生成排行榜键
   */
  leaderboard(name: string, period?: string): string {
    const parts = ['leaderboard', name];
    if (period) {
      parts.push(period);
    }
    return this.generate(...parts);
  }

  /**
   * 生成限流键
   */
  rateLimit(identifier: string, window: string): string {
    return this.generate('ratelimit', identifier, window);
  }

  /**
   * 生成分布式锁键
   */
  lock(resource: string): string {
    return this.generate('lock', resource);
  }

  /**
   * 生成发布订阅频道键
   */
  channel(name: string): string {
    return this.generate('channel', name);
  }

  /**
   * 生成标签键
   */
  tag(tagName: string): string {
    return this.generate('tag', tagName);
  }

  /**
   * 生成监控指标键
   */
  metric(name: string, timestamp?: number): string {
    const parts = ['metric', name];
    if (timestamp) {
      parts.push(timestamp.toString());
    }
    return this.generate(...parts);
  }

  /**
   * 生成临时键
   */
  temp(identifier: string): string {
    return this.generate('temp', identifier, Date.now().toString());
  }

  /**
   * 解析键获取组件
   */
  parse(key: string): string[] {
    return key.split(this.options.separator);
  }

  /**
   * 检查键是否匹配模式
   */
  matches(key: string, pattern: string): boolean {
    // 简单的通配符匹配
    const regexPattern = pattern.replace(/\*/g, '.*').replace(/\?/g, '.');

    const regex = new RegExp(`^${regexPattern}$`);
    return regex.test(key);
  }

  /**
   * 生成模式匹配字符串
   */
  pattern(...parts: (string | '*')[]): string {
    return this.generate(...parts);
  }

  /**
   * 创建子生成器
   */
  child(options: Partial<KeyOptions>): KeyGenerator {
    return new KeyGenerator({
      ...this.options,
      ...options,
    });
  }
}

// 默认键生成器
export const defaultKeyGenerator = new KeyGenerator();

// 预定义的键生成器
export const cacheKeyGenerator = new KeyGenerator({ prefix: 'cache' });
export const sessionKeyGenerator = new KeyGenerator({ prefix: 'session' });
export const queueKeyGenerator = new KeyGenerator({ prefix: 'queue' });
export const lockKeyGenerator = new KeyGenerator({ prefix: 'lock' });

/**
 * 生成唯一ID
 */
export function generateId(): string {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
}

/**
 * 生成时间戳键
 */
export function generateTimestampKey(prefix: string, timestamp?: Date): string {
  const ts = timestamp ?? new Date();
  return `${prefix}:${ts.getTime()}`;
}

/**
 * 生成日期键
 */
export function generateDateKey(
  prefix: string,
  date?: Date,
  format: 'YYYY-MM-DD' | 'YYYY-MM' | 'YYYY' = 'YYYY-MM-DD'
): string {
  const d = date ?? new Date();
  let dateStr: string;

  switch (format) {
    case 'YYYY':
      dateStr = d.getFullYear().toString();
      break;
    case 'YYYY-MM':
      dateStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      break;
    case 'YYYY-MM-DD':
    default:
      dateStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      break;
  }

  return `${prefix}:${dateStr}`;
}
